import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wu_you/http/http.dart';
import 'package:wu_you/model/home/composite_model.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/utils/cache_util.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/power_linear_progress_indicator.dart';
import 'package:open_file/open_file.dart';
import 'package:toast/toast.dart';
import 'package:url_launcher/url_launcher.dart';

class UpdateVersionView extends StatefulWidget {
  final NewVersionModel model;

  UpdateVersionView(this.model, {Key key}) : super(key: key);

  @override
  _UpdateVersionViewState createState() => _UpdateVersionViewState();
}

class _UpdateVersionViewState extends State<UpdateVersionView> {
  NewVersionModel _model;
  int _downloadProgress = 0; //0..100
  String _savedPath;

  @override
  void initState() {
    super.initState();
    _model = widget.model;
  }

  @override
  Widget build(BuildContext context) {
    Widget updateChild;
    switch (_downloadProgress) {
      case 100:
        updateChild = ElevatedButton(
          onPressed: () {
            if (Platform.isIOS) {
              _onIosInstall();
            } else {
              _onAndroidInstall();
            }
          },
          child: Text("安装"),
        );
        break;
      case 0:
        updateChild = ElevatedButton(
          onPressed: () {
            if (Platform.isIOS) {
              _onIosInstall();
            } else {
              _onAndroidUpdate(context);
            }
          },
          child: Text("立即升级"),
        );
        break;
      default:
        updateChild = Text(
          "$_downloadProgress%",
          style: Theme.of(context).textTheme.headline2,
        );
        break;
    }

    Widget updateView = SizedBox.fromSize(
      size: Size(160, 40),
      child: PowerLinearProgressIndicator(
        value: _downloadProgress / 100,
        valueColor: AlwaysStoppedAnimation(AppColors.versionBtn),
        backgroundColor: Colors.transparent,
        center: updateChild,
        borderWidth: 1,
        borderColor: Colors.white,
        borderRadius: 20,
      ),
    );

    return Material(
      color: Colors.transparent,
      child: WillPopScope(
        child: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Padding(
                padding: EdgeInsets.only(left: 32, right: 32, bottom: 8),
                child: AspectRatio(
                  aspectRatio: 0.78,
                  child: Container(
                    margin: EdgeInsets.only(bottom: 8),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(
                          Utils.getImgPath('background_new_version'),
                        ),
                        fit: BoxFit.fill,
                      ),
                    ),
                    child: Stack(
                      children: [
                        Align(
                          alignment: Alignment.centerLeft,
                          child:
                          Container(padding:EdgeInsets.only(left: 32,right: 32),height: 150,child:
                              SingleChildScrollView(child:
                         Text(
                              "${_model.update_log}",
                              style: Theme.of(context).textTheme.headline6,
                            ),
                          )),
                        ),
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Padding(
                            padding: EdgeInsets.only(bottom: 16),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                updateView,
                                Padding(
                                  padding: EdgeInsets.only(top: 8),
                                  child: Text(
                                    "WiFi环境下更新更快哦~",
                                    style: Theme.of(context).textTheme.headline2,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              Offstage(
                offstage: _model.force_update == "1" ? true : false,
                child: CloseButton(
                  color: Colors.white,
                ),
              )
            ],
          ),
        ),
        onWillPop: () async {
          return _model.force_update == "1" ? false: true;
        },
      ),
    );
  }

  void _onIosUpdate(BuildContext context) async {
    String url = _model.download_url;
    if (url.startsWith("sss")) {
      _updateByAppStore();
    } else {
      _updateByDownload();
    }
  }

  ///
  void _updateByAppStore() {}

  void _updateByDownload() {
    showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime.now(),
      lastDate: DateTime.now()..add(Duration(days: 1)),
      locale: Locale('zh', 'CH'),
    );
  }

  void _onAndroidUpdate(BuildContext context) async {
    String url = _model.download_url;
    String fileName = "jj_${_model.version_name.replaceAll(".", "_")}.apk";
    _savedPath = await CacheUtil.getDownloadPath(fileName);
    bool exists = await File(_savedPath).exists();
    if (exists) {
      setState(() {
        _downloadProgress = 100;
      });
      return;
    }
    Http(useToken: false).download(
      url,
      _savedPath,
      onReceiveProgress: (int count, int total) {
        double progress = count / total;
        setState(() {
          _downloadProgress = (progress * 100).toInt();
        });
      },
      options: Options(
        headers: {},
        responseType: ResponseType.stream,
        receiveTimeout: 15 * 60 * 1000, //超时时间15分钟
      ),
    );
  }

  void _onIosInstall() async {
    if (await canLaunch(_model.download_url)) {
      await launch(_model.download_url);
    }
  }

  void _onAndroidInstall() async {
    File file = File(_savedPath);
    if (!file.existsSync()) {
      Toast.show("安装包不存在,请重新下载", context);
      return;
    }
    OpenFile.open(file.path);
  }
}
